use tauri::Manager;
use utils::download_manager::DownloadManager;

mod handlers;
mod models;
mod utils;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_cli::init())
        .plugin(tauri_plugin_window_state::Builder::new().build())
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_clipboard_manager::init())
        .manage(utils::download_manager::DownloadManager::new())
        .invoke_handler(tauri::generate_handler![
            handlers::category::get_all_categories,
            handlers::category::get_category_apps,
            handlers::category::get_all_apps,
            handlers::server::get_target_arch_to_store,
            handlers::server::get_json_server_url,
            handlers::server::get_img_server_url,
            handlers::app::get_app_info,
            handlers::app::search_all_apps,
            handlers::home::get_home_links,
            handlers::home::get_home_lists,
            handlers::home::get_home_list_apps,
            handlers::file::read_text_file,
            handlers::file::save_text_file,
            handlers::download::get_downloads,
            handlers::download::add_download,
            handlers::download::pause_download,
            handlers::download::resume_download,
            handlers::download::cancel_download,
            handlers::deb::check_is_installed,
            handlers::deb::check_launch_app,
            handlers::deb::launch_launch_app,
            utils::get_user_agent,
        ])
        .on_window_event(|window, event| match event {
            tauri::WindowEvent::Destroyed => {
                // 获取 DownloadManager 实例并关闭 aria2
                let download_manager = window.state::<DownloadManager>();
                download_manager.shutdown_aria2();
            }
            _ => {}
        })
        .setup(|app| {
            let app_handle = app.handle().clone();
            // 创建后台任务检查下载状态
            tauri::async_runtime::spawn(async move {
                loop {
                    {
                        let download_manager = app_handle.state::<DownloadManager>();
                        if download_manager.has_downloads() {
                            let _ = download_manager.get_downloads().await;
                        }
                    }
                    tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
                }
            });

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
